<?php
// 引入配置文件
require 'config.php';
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: ../login.html");
    exit();
}

// 创建PDO实例
try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
    // 设置错误模式为异常
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 准备SQL查询
    $sql = "SELECT * FROM kami"; // 假设你的卡密存储在名为kami的表中
    $stmt = $pdo->query($sql);
    
    // 获取查询结果
    $cardList = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 计算卡密的总数量
    $count = count($cardList);
    
    // 构建JSON格式的输出
    $output = [
        "code" => 200,
        "msg" => "",
        "count" => $count,
        "data" => $cardList
    ];
    
    // 设置响应头为JSON
    header('Content-Type: application/json');
    // 输出JSON数据
    echo json_encode($output, JSON_UNESCAPED_UNICODE);
    
} catch (PDOException $e) {
    // 错误处理
    $output = [
        "code" => 500,
        "msg" => $e->getMessage(),
        "count" => 0,
        "data" => []
    ];
    header('Content-Type: application/json');
    echo json_encode($output, JSON_UNESCAPED_UNICODE);
}
?>